package com.cicadamob.contact.api.group.asynctask;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.cicadamob.contact.api.Utils.ContactConfig;
import com.cicadamob.contact.api.Utils.StringUtil;
import com.cicadamob.contact.api.Utils.Logger.AppLogger;
import com.cicadamob.contact.api.Utils.NetWork.HttpRequestCallBack;
import com.cicadamob.contact.api.Utils.NetWork.HttpUtil;
import com.cicadamob.contact.api.Utils.NetWork.NetWorkUtil;
import com.cicadamob.contact.api.Utils.NetWork.HttpUtil.RequestMethod;
import com.cicadamob.contact.api.group.bean.Group;
import com.cicadamob.contact.api.group.bean.ResultModel;
import com.cicadamob.contact.api.group.dao.Group_Db_Dao;
import com.cicadamob.contact.api.group.http.Http_Group_Util;
import com.cicadamob.contact.api.group.http.JsonParseUtil;
import com.cicadamob.contact.api.service.Contact;
import com.cicadamob.contact.api.service.ServerUrl;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;

public class AddMemberRunnable{
	private Handler mHandler;
	private int what;
	private Context mContext;
	private String groupID;
	private Group_Db_Dao dbHelper;
	private List<Contact> selectedcontacts = new ArrayList<Contact>();  
 
	public AddMemberRunnable(Handler mHandler, int what, Context mContext,
			String groupID,List<Contact> selectedcontacts) {
		this.mHandler = mHandler;
		this.what = what;
		this.mContext = mContext;
	 
		this.groupID = groupID;
		
		this.selectedcontacts.clear();
		if(selectedcontacts!=null && selectedcontacts.size()>0)
			this.selectedcontacts.addAll(selectedcontacts);
	}

	public void run() {
		// TODO Auto-generated method stub
		dbHelper = Group_Db_Dao.getInstance(mContext);
		ResultModel resultmodel = new ResultModel();
		if (!NetWorkUtil.isConnected(mContext)) {
			resultmodel.setRetcode(100);
			return;// 网络异常
		}
		
//		selectedcontacts.clear();
//		Iterator iter = AddSysContactActivity.gridViewData.keySet().iterator();
//		while (iter.hasNext()) {
//			Object key = iter.next();
//			Contact val = AddSysContactActivity.gridViewData.get(key);
//			if (val.isCancelByUser()) {
//				selectedcontacts.add(val);
//			}
//		}
		mHandler.post(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				addGroupMemberRunable();
			}
		});
		

	}

	
	
	private void addGroupMemberRunable() {
		// TODO Auto-generated method stub
		String xmlData = Http_Group_Util.get_addGroupMemberXML(groupID,JsonParseUtil.contactsTOjson(selectedcontacts));
		Map<String, String> requestMap = new HashMap<String, String>();
		requestMap.put(HttpUtil.XML, xmlData);
		 AppLogger.writeLogToFile(mContext, ContactConfig.DIRECTORY+"/httpGroupLog", "msg_group", "发送报文  url =" + ServerUrl.ADD_GROUP_MEMBER
		    		+"\r\n xml ="+xmlData, true);
		HttpUtil.HttpRequest(mContext, RequestMethod.POST,
				ServerUrl.ADD_GROUP_MEMBER, true, requestMap,
				new HttpRequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						// TODO Auto-generated method stub
						doResult(responseInfo.result);
						AppLogger.writeLogToFile(mContext, ContactConfig.DIRECTORY+"/httpGroupLog", "msg_group", "响应报文  url =" + ServerUrl.ADD_GROUP_MEMBER
					    		+"\r\n xml ="+responseInfo.result, true);	
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						// TODO Auto-generated method stub
						ResultModel resultmodel =new ResultModel();
						resultmodel.setRetcode(-8);
						sendResultMessage(resultmodel);
					}

				});
}
	
	
	
	private void getGroupMember( final ResultModel addResultModel) {
       
		String xmlData = Http_Group_Util.get_getGroupMemberXML(groupID,dbHelper.getQueryMemberTimeStamp(groupID));
		Map<String, String> requestMap = new HashMap<String, String>();
		requestMap.put(HttpUtil.XML, xmlData);
 		HttpUtil.HttpRequest(mContext, RequestMethod.POST,
				ServerUrl.GET_GROUP_MEMBER, true, requestMap,
				new HttpRequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						// TODO Auto-generated method stub
						ResultModel groupResultModel = Http_Group_Util.parseResult(responseInfo.result);
				 		// 群组不存在或已经被删除
						if (groupResultModel.getRetcode() == 3) {
							// dismissHandlerLoadingDialog();
				 			dbHelper.delGroupById(groupID);
				 			sendResultMessage(addResultModel);
							return;
						}

						if (groupResultModel.getRetcode() == 0) {
							String SqlStr = groupResultModel.getGroupmembers();
							dbHelper.updateVersion(groupID,
									groupResultModel.getLastupdatetime());
							if (!StringUtil.isEmpty(SqlStr)) {
								dbHelper.delTempMember(groupID);
								dbHelper.executesql(JsonParseUtil.jsonTOStringMemberList(SqlStr));
							}
							List<Contact> contacts=dbHelper.queryAllMemberByGroupId(groupID);
					 		addResultModel.setResultData(contacts);
						}
						sendResultMessage(addResultModel);
						
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						// TODO Auto-generated method stub
						ResultModel groupResultModel=new ResultModel();
						groupResultModel.setRetcode(-8);
						sendResultMessage(groupResultModel);
					}

				});

	}
	
	
	public void sendResultMessage(ResultModel mResult) {
		mHandler.obtainMessage(what, mResult).sendToTarget();
	}

	private void doResult(String result) {
		ResultModel resultmodel = new ResultModel();

		resultmodel = Http_Group_Util.parseResult(result);
		// 如果群组已经被删除
		if (resultmodel.getRetcode() == 3) {
			sendResultMessage(resultmodel);
			return;
		}
		

		if (resultmodel.getRetcode() == 6
				|| resultmodel.getRetcode() == 0) {// 有重复成员
			// 发送广播通知 群组消息更新相关信息
			final List<Contact> memberList = new ArrayList<Contact>();
			memberList.addAll(selectedcontacts);
			StringBuilder  addUserNameBuilder=new StringBuilder();
			for(Contact contact : selectedcontacts){
				if(!StringUtil.isEmpty(contact.getDisplayName())){
					addUserNameBuilder.append(contact.getDisplayName()+",");
				}
			}
			if(addUserNameBuilder.length()>0){
				addUserNameBuilder.deleteCharAt(addUserNameBuilder.length()-1);
			}
			
			if(addUserNameBuilder.length()>20){
				addUserNameBuilder.delete(20, addUserNameBuilder.length()-1);
				addUserNameBuilder.append("...");
			}
			
			final Group group = new Group();
			Group_Db_Dao dbHelper=Group_Db_Dao.getInstance(mContext);
			group.setGroup_id(groupID);
		/*	通知消息界面更新消息
		 * PushMessageModel message = new PushMessageModel();
			message.setGroupName(dbHelper.queryGroupNameAndImage(AddSendContactActivity.groupid).getGroup_name());
			message.setGroupUserName(addUserNameBuilder.toString());
			final String tips = PushUtils.getNoticeTips(2, message);
			mHandler.post(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					PushUtils.MsgSyncGroupOrMember(mContext, 2, group,
							memberList,tips,false);
				}
			});*/
		
		     getGroupMember(resultmodel);
		} else if (resultmodel.getRetcode() != 0) {
			sendResultMessage(resultmodel);
		}
		

	}

}
